package com.sinosoft.taxbenefit.core.bargaincheckquery.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.EBResultCodeDTO;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.bargaincheckquery.ReqBargainCheckQueryDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.response.bargaincheckquery.ResBargainCheckDetailDTO;
import com.sinosoft.taxbenefit.api.dto.response.bargaincheckquery.ResBargainCheckQueryDTO;
import com.sinosoft.taxbenefit.api.dto.response.bargaincheckquery.ResBargainCheckTotalDTO;
import com.sinosoft.taxbenefit.core.bargaincheckquery.biz.service.BargainCheckQueryCoreService;
import com.sinosoft.taxbenefit.core.bargaincheckquery.dto.ReqBargainCheckDTO;
import com.sinosoft.taxbenefit.core.bargaincheckquery.dto.ResultBargainCheckDTO;
import com.sinosoft.taxbenefit.core.bargaincheckquery.dto.ResultBargainCheckDetailDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.BusinessCheckService;
import com.sinosoft.taxbenefit.core.ebaowebservice.BusinesssCheckService;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;

@Service
public class BargainCheckQueryCoreServiceImpl extends TaxBaseService implements BargainCheckQueryCoreService{
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	FaultTaskService faultTaskService;

	@Override
	public ThirdSendResponseDTO bargainCheckQuery(ReqBargainCheckQueryDTO reqBargainCheckQueryDTO,ParamHeadDTO paramHead) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			logger.info("交易核对信息查询（核心请求）JSON 体数据内容："+JSONObject.toJSONString(reqBargainCheckQueryDTO));
			//1.核心DTO转换中保信DTO
			ReqBargainCheckDTO reqBargainCheckDTO = convertCarrier(reqBargainCheckQueryDTO);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.BARGAIN_CHECK_QUERY.code(), paramHead, reqBargainCheckDTO);
			logger.info("交易核对信息查询（请求中保信）JSON 数据内容："+JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.BARGAIN_CHECK_QUERY.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			BusinesssCheckService service = new BusinesssCheckService(wsdlLocation);
			BusinessCheckService servicePort = service.getBusinessCheckServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.businessCheck(thirdSendDTO.getHead(), thirdSendDTO.getBody(), responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("交易核对信息查询（中保信响应）JSON 数据内容："+responseBody.getJsonString());
			//封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			//封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.POLICY_IN_TRANSFER_UPLOAD.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			//3.封装返回核心dto;
			if(ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())){
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			}else if(ENUM_RESULT_CODE.HEADER_ERROR.code().equals(responseHeader.getResultCode())){
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				StringBuffer sbStr = new StringBuffer(); 
				for(String mess : responseHeader.getResultMessage().getMessage()){
					sbStr.append(mess).append("|");
				}
				String message = sbStr.substring(0, sbStr.length()-1).toString();
				thirdSendResponse.setResultDesc(message);
			} else {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			}
			if(!StringUtil.isEmpty(responseBody.getJsonString())){
				ResBargainCheckQueryDTO resBargainCheckQuery = new ResBargainCheckQueryDTO();
				ResultBargainCheckDTO resBargainCheckDTO = JSONObject.parseObject(responseBody.getJsonString(), ResultBargainCheckDTO.class);
				EBResultCodeDTO eBResultCode = resBargainCheckDTO.getResult();
				HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
				hxResultCode.setResultCode(eBResultCode.getResultCode());
				String message = "";
				if(null != eBResultCode.getResultMessage()){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : eBResultCode.getResultMessage()){
						sbStr.append(mess).append("|");
					}
					message = sbStr.substring(0, sbStr.length()-1).toString();
				}
				hxResultCode.setResultMessage(message);
				resBargainCheckQuery.setResult(hxResultCode);
				//获取业务数据
				if(resBargainCheckDTO.getTotal() != null) {
					ResBargainCheckTotalDTO resBargainCheckTotalDTO = new ResBargainCheckTotalDTO();
					resBargainCheckTotalDTO.setCheckDate(resBargainCheckDTO.getTotal().getCheckDate());
					resBargainCheckTotalDTO.setCompanyCode(resBargainCheckDTO.getTotal().getCompanyCode());
					resBargainCheckTotalDTO.setFailNum(resBargainCheckDTO.getTotal().getFailNum());
					resBargainCheckTotalDTO.setSuccessNum(resBargainCheckDTO.getTotal().getSuccessNum());
					resBargainCheckTotalDTO.setTotalNum(resBargainCheckDTO.getTotal().getTotalNum());
					resBargainCheckQuery.setTotal(resBargainCheckTotalDTO);
				}
				if(resBargainCheckDTO.getDetail() != null) {
					List<ResBargainCheckDetailDTO> resBargainCheckDetailList = new ArrayList<ResBargainCheckDetailDTO>();
					for (ResultBargainCheckDetailDTO resultBargainCheckDetailDTO : resBargainCheckDTO.getDetail()) {
						ResBargainCheckDetailDTO resBargainCheckDetailDTO = new ResBargainCheckDetailDTO();
						resBargainCheckDetailDTO.setCheckTransType(resultBargainCheckDetailDTO.getCheckTransType());
						resBargainCheckDetailDTO.setClaimNo(resultBargainCheckDetailDTO.getClaimNo());
						resBargainCheckDetailDTO.setComFeeId(resultBargainCheckDetailDTO.getComFeeId());
						resBargainCheckDetailDTO.setEndorsementNo(resultBargainCheckDetailDTO.getEndorsementNo());
						resBargainCheckDetailDTO.setErrorMessage(resultBargainCheckDetailDTO.getErrorMessage());
						resBargainCheckDetailDTO.setFeeId(resultBargainCheckDetailDTO.getFeeId());
						resBargainCheckDetailDTO.setFeeStatus(resultBargainCheckDetailDTO.getFeeStatus());
						resBargainCheckDetailDTO.setPolicyNo(resultBargainCheckDetailDTO.getPolicyNo());
						resBargainCheckDetailDTO.setRenewalEndorsementNo(resultBargainCheckDetailDTO.getRenewalEndorsementNo());
						resBargainCheckDetailDTO.setReturnCode(resultBargainCheckDetailDTO.getReturnCode());
						resBargainCheckDetailDTO.setSequenceNo(resultBargainCheckDetailDTO.getSequenceNo());
						resBargainCheckDetailDTO.setTransDate(resultBargainCheckDetailDTO.getTransDate());
						resBargainCheckDetailList.add(resBargainCheckDetailDTO);
					}
					resBargainCheckQuery.setDetail(resBargainCheckDetailList);
				}
				thirdSendResponse.setResJson(resBargainCheckQuery);
			}
		} catch (Exception e) {
			logger.error("交易核对信息查询后置处理发生异常!");
			e.printStackTrace();
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
		}
		logger.error("交易核对信息查询后置处理结束!");
		return thirdSendResponse;
	}
	
	/**
	 * 核心DTO转中保信DTO
	 * @param reqBargainCheckQueryDTO
	 * @return
	 */
	public ReqBargainCheckDTO convertCarrier(ReqBargainCheckQueryDTO reqBargainCheckQueryDTO){
		ReqBargainCheckDTO reqBargainCheckDTO = new ReqBargainCheckDTO();
		reqBargainCheckDTO.setCheckDate(reqBargainCheckQueryDTO.getCheckDate());
		reqBargainCheckDTO.setComFailNum(reqBargainCheckQueryDTO.getComFailNum());
		reqBargainCheckDTO.setComSuccessNum(reqBargainCheckQueryDTO.getComSuccessNum());
		reqBargainCheckDTO.setRequestTotalNum(reqBargainCheckQueryDTO.getRequestTotalNum());
		return reqBargainCheckDTO;
	}
}